package handler

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"zk/api/result"
	"zk/internal/dao"
	"zk/internal/model"
)

func Register(c *gin.Context) {
	var req result.RegisterReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "验证失败",
			"date": err.Error(),
		})
		return
	}
	user := dao.GetUserBy(req.Name)
	if user.ID != 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "用户已存在",
			"date": nil,
		})
		return
	}
	user = model.User{
		Name:     req.Name,
		Password: req.Password,
	}
	if !dao.CreateUser(&user) {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "注册失败",
			"date": nil,
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "注册成功",
		"date": user,
	})
}

func Login(c *gin.Context) {
	var req result.RegisterReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "验证失败",
			"date": err.Error(),
		})
		return
	}
	user := dao.GetUserBy(req.Name)
	if user.ID == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "用户不存在",
			"date": nil,
		})
		return
	}
	user = model.User{
		Name:     req.Name,
		Password: req.Password,
	}
	if !dao.GetUserByNameAndPassword(req.Name, req.Password) {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "用户名密码错误",
			"date": nil,
		})
		return
	}
	//token,_:=pkg.NewJWT()
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"date": "user",
	})
}
